package net.goutalk.glcs.module.erpModel.caseErpPurchase.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.model.result.R;
import net.goutalk.glcs.common.page.PageOutput;
import net.goutalk.glcs.common.utils.VoToColumnUtil;
import net.goutalk.glcs.module.erpModel.caseErpPurchase.dto.AddCaseErpApplyDto;
import net.goutalk.glcs.module.erpModel.caseErpPurchase.dto.CaseErpApplyPageDto;
import net.goutalk.glcs.module.erpModel.caseErpPurchase.dto.UpdateCaseErpApplyDto;
import net.goutalk.glcs.module.erpModel.caseErpPurchase.entity.CaseErpApply;
import net.goutalk.glcs.module.erpModel.caseErpPurchase.service.ICaseErpPurchaseApplyService;
import net.goutalk.glcs.module.erpModel.caseErpPurchase.vo.CaseErpApplyDetailVo;
import net.goutalk.glcs.module.erpModel.caseErpPurchase.vo.CaseErpApplyPageVo;
import net.goutalk.glcs.module.erpModel.caseErpPurchase.vo.CaseErpApplyVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
* @title: 采购申请
* @Author 管理员
* @Date: 2023-07-20
* @Version 1.0
*/
@RestController
@RequestMapping(GlobalConstant.CASE_ERP_PURCHASE_APPLY +"/caseErpPurchaseApply")
@Api(value = GlobalConstant.CASE_ERP_PURCHASE_APPLY +"/caseErpPurchaseApply", tags = "采购申请")
@AllArgsConstructor
public class CaseErpPurchaseApplyController {

    private final ICaseErpPurchaseApplyService caseErpPurchaseApplyService;


    @GetMapping(value = "/list")
    @ApiOperation(value="CaseErpApply列表(不分页)")
    public R list(){
        List<CaseErpApply> list = caseErpPurchaseApplyService.list();
        return R.ok(list);
    }

    @GetMapping(value = "/page")
    @ApiOperation(value="CaseErpApply列表(分页)")
    @SaCheckPermission("purchasingapply:detail")
    public R page(@Valid CaseErpApplyPageDto dto){

        LambdaQueryWrapper<CaseErpApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(StrUtil.isNotBlank(dto.getApplyNumber()), CaseErpApply::getApplyNumber,dto.getApplyNumber())
                .eq(ObjectUtil.isNotNull(dto.getIsSysNum()), CaseErpApply::getIsSysNum,dto.getIsSysNum())
                .like(StrUtil.isNotBlank(dto.getTheme()), CaseErpApply::getTheme,dto.getTheme())
                .between(ObjectUtil.isNotNull(dto.getApplyDateStart()) && ObjectUtil.isNotNull(dto.getApplyDateEnd()), CaseErpApply::getApplyDate,dto.getApplyDateStart(),dto.getApplyDateEnd())
                .like(StrUtil.isNotBlank(dto.getApplyUserIds()), CaseErpApply::getApplyUserIds,dto.getApplyUserIds())
                .eq(ObjectUtil.isNotNull(dto.getApplyDepId()), CaseErpApply::getApplyDepId,dto.getApplyDepId())
                .eq(ObjectUtil.isNotNull(dto.getRelatedProject()), CaseErpApply::getRelatedProject,dto.getRelatedProject())
                .like(StrUtil.isNotBlank(dto.getRemark()), CaseErpApply::getRemark,dto.getRemark())
                    .orderByDesc(CaseErpApply::getId)
                .select(CaseErpApply.class, x -> VoToColumnUtil.fieldsToColumns(CaseErpApplyPageVo.class).contains(x.getProperty()));
        List<CaseErpApply> list = caseErpPurchaseApplyService.list(queryWrapper);
        List<CaseErpApplyPageVo> caseErpApplyPageVos = BeanUtil.copyToList(list, CaseErpApplyPageVo.class);
        //转换
        caseErpApplyPageVos = caseErpPurchaseApplyService.convert(caseErpApplyPageVos);
        PageOutput<CaseErpApplyPageVo> output = new PageOutput<>();
        output.setCurrentPage(dto.getLimit());
        output.setPageSize(dto.getSize());
        output.setTotal(list.size());
        output.setList(caseErpApplyPageVos);
        return R.ok(output);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询CaseErpApply信息")
    @SaCheckPermission("purchasingapply:detail")
    public R info(@RequestParam Long id){
        CaseErpApply caseErpApply = caseErpPurchaseApplyService.getByIdDeep(id);
        if (caseErpApply == null) {
           return R.error("找不到此数据！");
        }
        CaseErpApplyVo caseErpApplyVo = BeanUtil.toBean(caseErpApply, CaseErpApplyVo.class);
        caseErpApplyVo = caseErpPurchaseApplyService.convertInfo(caseErpApplyVo);
        if (CollectionUtil.isNotEmpty(caseErpApplyVo.getCaseErpApplyDetailList())){
            List<CaseErpApplyDetailVo> caseErpApplyDetailList = caseErpApplyVo.getCaseErpApplyDetailList();
            BigDecimal amountSum = BigDecimal.ZERO;
            BigDecimal countSum = BigDecimal.ZERO;
            for (CaseErpApplyDetailVo caseErpApplyDetailVo : caseErpApplyDetailList) {
                if (ObjectUtil.isNotEmpty(caseErpApplyDetailVo.getAmount())){
                    amountSum = amountSum.add(caseErpApplyDetailVo.getAmount());
                }
                if (ObjectUtil.isNotEmpty(caseErpApplyDetailVo.getCount())){
                    countSum = countSum.add(caseErpApplyDetailVo.getCount());
                }
            }
            caseErpApplyVo.setAmountSum(amountSum);
            caseErpApplyVo.setCountSum(countSum);
        }
        return R.ok(caseErpApplyVo);
    }


    @PostMapping
    @ApiOperation(value = "新增CaseErpApply")
    @SaCheckPermission("purchasingapply:add")
    public R add(@Valid @RequestBody AddCaseErpApplyDto dto){
        CaseErpApply caseErpApply = BeanUtil.toBean(dto, CaseErpApply.class);
        return R.ok(caseErpPurchaseApplyService.add(caseErpApply));

    }

    @PutMapping
    @ApiOperation(value = "修改CaseErpApply")
    @SaCheckPermission("purchasingapply:edit")
    public R update(@Valid @RequestBody UpdateCaseErpApplyDto dto){

        CaseErpApply caseErpApply = BeanUtil.toBean(dto, CaseErpApply.class);
        return R.ok(caseErpPurchaseApplyService.update(caseErpApply));

    }

    @DeleteMapping
    @ApiOperation(value = "删除")
    @SaCheckPermission("purchasingapply:delete")
    public R delete(@Valid @RequestBody List<Long> ids){
        return R.ok(caseErpPurchaseApplyService.delete(ids));

    }

    @GetMapping("/export")
    @ApiOperation(value = "导出")
    public ResponseEntity<byte[]> exportData(@Valid CaseErpApplyPageDto dto, @RequestParam(defaultValue = "false") Boolean isTemplate) {
        List<CaseErpApplyPageVo> customerList = isTemplate != null && isTemplate ? new ArrayList<>() : ((PageOutput<CaseErpApplyPageVo>) page(dto).getData()).getList();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        customerList = caseErpPurchaseApplyService.convert(customerList);
        EasyExcel.write(bot, CaseErpApplyPageVo.class).automaticMergeHead(false).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(customerList);
        return R.fileStream(bot.toByteArray(), "采购申请" + ExcelTypeEnum.XLSX.getValue());
    }
}